// 云函数/getQuestionsManage/index.js
'use strict';
const db = uniCloud.database();

// 答案转换方法
function normalizeAnswer(item) {
  if (item.type === 'single') {
    const index = item.options.findIndex(opt => opt === item.answer)
    return index !== -1 ? [index] : []
  }
  
  if (item.type === 'judge') {
    return item.answer === '正确' ? [0] : [1]
  }
  
  return []
}

exports.main = async (event, context) => {
  try {
    const { 
      searchKey = '',
      filterType = 0 
    } = event

    // 构建查询条件
    const query = {}
    const typeMap = { 1: 'single', 2: 'judge' }
    
    if (filterType > 0) query.type = typeMap[filterType]
    if (searchKey) {
      query.question = db.RegExp({
        regexp: searchKey,
        options: 'i'
      })
    }

    // 获取总数
    const countRes = await db.collection('questions').where(query).count()
    
    // 获取数据
    const listRes = await db.collection('questions')
      .where(query)
      .field({
        options: true,
        type: true,
        status: true,
        createTime: true,
        answer: true,
        text:true,
      })
      .orderBy('createTime', 'desc')
      .get()

    // 转换数据格式
    const transformedList = listRes.data.map(item => ({
      id: item._id,
      text: item.text,
      type: item.type,
      options: item.options,
      answer: item.answer,
      status: item.status,
      createTime: item.createTime
    }))

    return {
      code: 0,
      data: {
        list: transformedList,
        total: countRes.total
      }
    }
    
  } catch (e) {
    console.error('云函数错误：', e)
    return {
      code: -1,
      msg: '获取题目失败',
      data: null
    }
  }
}